import { JsonController, QueryParam, Body, Get, Put, Post } from 'routing-controllers';
import { UserService } from '../service/user.service';
import { UserEntity } from '../utils/repository';
import { sign } from '../utils/auth';
import { Code, CodeMessage } from '../utils/code';
import { Result } from '../utils/result';
import { Service, Inject } from 'typedi';

@Service()
@JsonController('/user')
export class UserController {
  @Inject()
  userService: UserService;

  @Post('/login')
  async login(@Body() entity: UserEntity) {
    const record = await this.userService.login(entity);
    if (record) {
      const payload = { id: record.uid, username: record.username };
      const access_token = sign(payload);
      const refresh_token = sign(payload, { expiresIn: '1d' });
      return Result.ok(Code.SUCCESS, '登录成功', {
        access_token,
        refresh_token,
      });
    }
    return Result.fail(Code.ERROR_USER_LOGIN, CodeMessage[Code.ERROR_USER_LOGIN]);
  }

  @Post('/register')
  async register(@Body() entity: UserEntity) {
    const index = await this.userService.register(entity);
    if (index == 1) {
      return Result.ok(Code.SUCCESS, '注册成功');
    }
    return Result.fail(Code.ERROR_USER_REGISTER, CodeMessage[Code.ERROR_USER_REGISTER]);
  }

  @Put('/update')
  async update(@QueryParam('id') id: string, @Body() user: UserEntity) {
    const index = await this.userService.update(id, user);
    if (index == 1) {
      return Result.ok(Code.SUCCESS, '更新成功');
    }
    return Result.fail(Code.ERROR_USER_UPDATE, CodeMessage[Code.ERROR_USER_UPDATE]);
  }

  @Get('/select')
  async select(@QueryParam('id') id?: string) {
    const result = await this.userService.select(id);
    if (result) {
      return Result.ok(Code.SUCCESS, '获取成功', result);
    }
    return Result.fail(Code.ERROR_USER_SELECT, CodeMessage[Code.ERROR_USER_SELECT]);
  }
}
